package handler

import (
	"2302a/tiktok_business/api/request"
	"2302a/tiktok_business/api/resp"
	"2302a/tiktok_business/consts"
	"2302a/tiktok_business/global"
	"2302a/tiktok_business/internal/dao"
	"2302a/tiktok_business/internal/model"
	"2302a/tiktok_business/pkg"
	"context"
	"github.com/gin-gonic/gin"
	"math/rand"
	"net/http"
	"regexp"
	"strconv"
	"time"
)

func UserRegister(c *gin.Context) {
	var req request.UserRegisterReq
	err := c.ShouldBind(&req)
	if err != nil {
		resp.Error(c, http.StatusUnauthorized, "参数信息错误", err.Error())
		return
	}
	var user model.Users
	dao.GetOneByField(&model.Users{Phone: req.Phone}, &user)
	if user.UserId > 0 {
		resp.Error(c, http.StatusBadRequest, "用户已存在", false)
		return
	}

	users := model.Users{
		Phone:        req.Phone,
		Password:     pkg.Md5Encryption(req.Password + "jfs9fg"), //加密+加盐
		Nickname:     req.Nickname,
		AvatarUrl:    req.AvatarUrl,
		Region:       req.Region,
		Introduction: req.Introduction,
	}
	dao.Create(&users)
	if pkg.Md5Encryption(req.Password) != pkg.Md5Encryption(req.Confirm) {
		resp.Error(c, http.StatusBadRequest, "密码不一致", false)
		return
	}
	resp.Success(c, "注册成功", true)

}

func UserLogin(c *gin.Context) {
	//获取参数信息
	var req request.UserLoginReq
	err := c.ShouldBind(&req)
	//判断信息是否为空
	if err != nil {
		resp.Error(c, http.StatusUnauthorized, "参数信息错误", err.Error())
		return
	}
	compile := regexp.MustCompile(`^1\d{10}$`).Find([]byte(req.Phone))
	if len(compile) != 11 {
		resp.Error(c, http.StatusUnauthorized, "手机号格式校验（支持 11 位国内手机号）", false)
		return
	}
	var user model.Users
	dao.GetOneByField(&model.Users{Phone: req.Phone}, &user)
	//判断用户是否注册没有请先去注册
	if user.UserId == 0 {
		resp.Error(c, http.StatusBadRequest, "账号或者密码错误，请求注册", false)
		return
	}
	//判断密码是否跟用户表里的一致
	if user.Password != pkg.Md5Encryption(req.Password+"jfs9fg") {
		resp.Error(c, http.StatusBadRequest, "账号或者密码错误", false)
		return
	}
	//验证通过则生成登录凭证（含用户 ID、登录时间）
	token := pkg.CreateJwtToken(user.UserId, 24*time.Hour, consts.JWT_KEY)
	//设置 2 小时过期时间，用户请求时需携带凭证
	global.RDB.Set(context.Background(), "login"+req.Phone, token, time.Hour*2)
	resp.Success(c, "登录成功", token)
}

func SendSms(c *gin.Context) {
	//获取参数信息
	var req request.SendSmsReq
	err := c.ShouldBind(&req)
	//判断信息是否为空
	if err != nil {
		resp.Error(c, http.StatusUnauthorized, "参数信息错误", err.Error())
		return
	}
	//随机数
	code := rand.Intn(9000) + 1000

	number, _ := global.RDB.Get(context.Background(), "sms_num"+req.Phone).Int()
	//限制一分钟只能发送一次
	if number >= 1 {
		resp.Error(c, http.StatusUnauthorized, "一分钟只能发送一次", false)
		return
	}
	//调用阿里云封装
	pkg.SendSms(req.Phone, strconv.Itoa(code))
	//存入redis中叫上值和验证码有限时间
	global.RDB.Set(context.Background(), "sendSms"+req.Phone, code, time.Minute*5)

	global.RDB.Info(context.Background(), "sms_num"+req.Phone)
	resp.Success(c, "短信成功", true)
}
func Personal(c *gin.Context) {
	var req request.PersonalReq
	err := c.ShouldBind(&req)
	if err != nil {
		resp.Error(c, http.StatusUnauthorized, "参数信息错误", err.Error())
		return
	}
	var user model.Users
	global.DB.Find(&user)
	if user.UserId == 0 {
		resp.Error(c, http.StatusBadRequest, "个人主页不存在", false)
		return
	}
	global.RDB.Set(context.Background(), "persona", model.Users{
		UserId:    user.UserId,
		Nickname:  user.Nickname,
		AvatarUrl: user.AvatarUrl,
		Region:    user.Region,
		VideoId:   user.VideoId,
		CountNum:  user.CountNum,
		FollowNum: user.FollowNum,
		FansNum:   user.FansNum,
	}, time.Hour*24)
	
	resp.Success(c, "个人主页成功", model.Users{
		UserId:    user.UserId,
		Nickname:  user.Nickname,
		AvatarUrl: user.AvatarUrl,
		Region:    user.Region,
		VideoId:   user.VideoId,
		CountNum:  user.CountNum,
		FollowNum: user.FollowNum,
		FansNum:   user.FansNum,
	})

}
